﻿using Microsoft.SqlServer.Types;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace QingZhouLinYe_Web
{
    public class LineConverter : ISugarDataConverter
    {
        public SugarParameter ParameterConverter<T>(Object value, int i)
        {
            var name = "@mylocationp" + i;
            var line = value as Line;
            //var wkt = location != null ? $"POINT ({location.X} {location.Y} {location.Z})" : null;

            var wkt = line != null ? $"{line.ToString()}" : null;
            Debug.WriteLine("wkt is :" + wkt);
            // 设置Value为SqlGeometry类型
            SqlGeometry geometry = null;
            if (line != null)
            {
                //string wkt = "POINT (37.7749 -122.4194)"; // 注意：WKT中的坐标顺序是(X Y)，但在地理上下文中是(经度 纬度)  
                // 创建一个SqlGeometry对象（这里使用WKT表示的点）  
                geometry = SqlGeometry.Parse(new SqlString(wkt));
                geometry.STSrid = 4490;
                geometry.MakeValid(); // MakeValid确保几何体是有效的  
            }
            var parameter = new SugarParameter(name, geometry)
            {
                UdtTypeName = "geometry",
                CustomDbType = System.Data.SqlDbType.Udt,
            };

            return parameter;
        }

        public T QueryConverter<T>(IDataRecord dr, int i)
        {
            var str = dr.GetValue(i).ToString();
            if (string.IsNullOrWhiteSpace(str))
            {
                return default;
            }

            //var parts = str.Replace("POINT(", "").Replace("POINT (", "").Replace("(", "").Replace(")", "").Split(' ');
            var partstr = str.Replace("LINESTRING (", "").Replace(")", "");
            var parts = partstr.Split(',');
            var poits = new Location[parts.Length];
            var line = new Line(poits);
            //for (int a = 0; a < parts.Length; a++)
            //{
            //    Debug.WriteLine("parts list"+a+" :" + parts[a].ToString());
            //}
            var poitstr = parts[0].Split(' ');
            if (poitstr.Length == 3 &&
            double.TryParse(poitstr[0], out var x) &&
            double.TryParse(poitstr[1], out var y) &&
            double.TryParse(poitstr[2], out var z))
            {
                poits[0] = new Location(x, y, z);
            }
            for (int a = 1; a < parts.Length; a++)
            {
                var poitstr1 = parts[a].Split(' ');
                if (poitstr1.Length == 4 &&
                double.TryParse(poitstr1[1], out var _x) &&
                double.TryParse(poitstr1[2], out var _y) &&
                double.TryParse(poitstr1[3], out var _z))
                {
                    poits[a] = new Location(_x, _y, _z);
                }
            }
            return (T)(object)line;

        }
    }
}